package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryList() {
        //1. 查询缓存
        String key = RedisConstants.CACHE_SHOP_TYPE_KEY;
        Long size = stringRedisTemplate.opsForList().size(key);

        //2. 命中则直接返回
        if (size!=null&&size>0) {
            List<String> typeList = stringRedisTemplate.opsForList().range(key, 0, size - 1);
            List<ShopType> shopTypeList = typeList.stream().map(s -> JSONUtil.toBean(s, ShopType.class)).collect(Collectors.toList());
            return shopTypeList;
        }

        //3. 未命中则查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();

        //4. 将查询类型集合放入redis中(此时就无所谓是否为空了)
        List<String> shopJsonList = typeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key,shopJsonList);

        //5. 返回
        return typeList;
    }
}
